package com.note.share.util;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Package：com.note.share.util
 * @Name：RedisUtils
 * @Author：热伊木
 * @Email：uyevan@163.com
 * @Date：2024-02-03-19:52
 * @Description：Redis工具类
 */
@SuppressWarnings("ALL")
@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;
    public static RedisUtils redisUtils;

    /*初始化方法*/
    @PostConstruct //执行一次
    private void init() {
        redisUtils = this;
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    }

    /**
     * 保存
     *
     * @param key
     * @param value
     * @param time
     * @param timeUnit
     */
    public static void save(String key, Object value, long time, TimeUnit timeUnit) {
        redisUtils.redisTemplate.opsForValue().set(key, value, time, timeUnit);
    }

    /**
     * 获取
     *
     * @param key
     * @param <T>
     * @return
     */
    public static <T> T get(String key) {
        ValueOperations<String, T> valueOperations = redisUtils.redisTemplate.opsForValue();
        return valueOperations.get(key);
    }

    /**
     * 移除
     *
     * @param key
     * @return
     */
    public static boolean remove(String key) {
        return redisUtils.redisTemplate.delete(key);
    }

    /**
     * 是否存在
     *
     * @param key
     * @return
     */
    public static boolean exists(String key) {
        return redisUtils.redisTemplate.hasKey(key);
    }

}
